function varargout = DrawMesh(varargin)
% This file is part of CISNE.
%
%     CISNE is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     any later version.
%
%     CISNE is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with CISNE.  If not, see <http://www.gnu.org/licenses/>.

% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal

% Edit the above text to modify the response to help DrawMesh

% Last Modified by GUIDE v2.5 16-Jul-2011 21:43:38

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @DrawMesh_OpeningFcn, ...
                   'gui_OutputFcn',  @DrawMesh_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before DrawMesh is made visible.
function DrawMesh_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for DrawMesh
handles.output = hObject;

parent=get(handles.figure1,'UserData');
handles.Path=parent.SetupWidget.getProjectPath();

axis(handles.axes1,'image','off');
axis(handles.cbar,'off');

warning('off','MATLAB:colorbar:DeprecatedV6Argument');
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes DrawMesh wait for user response (see UIRESUME)
%uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = DrawMesh_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in PB_Image.
function PB_Image_Callback(hObject, eventdata, handles)
%save mesh output as image
contents=get(handles.CB_Image,'String'); 
select=contents{get(handles.CB_Image,'Value')};
switch select
    case 'JPG'
        ext='*.jpg';
    case 'PNG'
        ext='*.png';
end
ext=fullfile(handles.Path,ext);
[filename, pathname] = uiputfile(ext,'Save picture as','default');
if isequal(filename,0) || isequal(pathname,0)
    return
end
im=getframe(handles.figure1,[299 5 572 541]);
imwrite(im.cdata,fullfile(pathname,filename));


% --- Executes on selection change in CB_Image.
function CB_Image_Callback(hObject, eventdata, handles)
% hObject    handle to CB_Image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns CB_Image contents as cell array
%        contents{get(hObject,'Value')} returns selected item from CB_Image


% --- Executes during object creation, after setting all properties.
function CB_Image_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_Image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function TL_Project_Callback(hObject, eventdata, handles)
% hObject    handle to TL_Project (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.
function TL_Project_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TL_Project (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in PB_Project.
function PB_Project_Callback(hObject, eventdata, handles)
% hObject    handle to PB_Project (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%load folder with output data (OUT)
outputdir=uigetdir(handles.Path,'Select folder with output data (OUT)');
set(handles.TL_Project,'String',outputdir);
if ~isempty(outputdir)
    %grab only first subrun of each run.
    Aux=dir(fullfile(outputdir,'01-*.tbl')); 
    if isempty(Aux)
        warndlg(['Selected folder doesn\''t contain SWAN output files\n' ...
            'Please select a folder with OUTPUT data.']);
        return
    end
else %project folder has not been selected. Exit function.
    return
end

TblList={Aux.name};    
m_list=cell(size(TblList));

%load run list.
for j=1:length(TblList)
    %remove subrun from run name (so it can be used as template).
    aux=regexp(TblList{j},'01-','split','once');
    TblList{j}=aux{2};
    aux=regexp(TblList{j},'-H','split');
    aux=regexp(aux{2},'T','split');
    H=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'D','split');
    T=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'Lvl','split');
    D=str2double(regexprep(aux{1},'_','\.'));
    
    m_list{j}=sprintf('H: %s || T: %s || D: %s',H,T,dir2txt(D));
end

set(handles.CB_SwanRun,'String',m_list);
handles.m_Tables=TblList;

%try to load computational grids' list
aux=regexp(TblList{1},'-H','split');
aux=aux{1};
projName=aux(1:end-3); %last 3 characters is run number. Ignore that.
fName=fullfile(outputdir,[projName '.cgl']);
if exist(fName,'file')
    fh=fopen(fName);
    k=0;
    while ~feof(fh)
        k=k+1;
        line=fgetl(fh);
        gridList{k}=line;
    end
else
    %no grid list file, use numbers only.
    auxList=dir(fullfile(outputdir,['*-' TblList{1}]));
    gridList=num2cell(1:length(auxList));
end
set(handles.CB_CGrid,'String',gridList);

%load parameters

Tbl=SWANTbl(fullfile(outputdir,['01-' TblList{1}]));
params=Tbl.header;
set(handles.CB_Mesh,'String',params);
set(handles.CB_Quiver,'String',params);

% Update handles structure
guidata(hObject, handles);




% --- Executes on selection change in CB_SwanRun.
function CB_SwanRun_Callback(hObject, eventdata, handles)
% hObject    handle to CB_SwanRun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


%updateDisplay(handles);

% --- Executes during object creation, after setting all properties.
function CB_SwanRun_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_SwanRun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function updateDisplay(handles)
%check if all needed data is available, if not, ignore this.
if  ~isempty(get(handles.CB_SwanRun,'String'))&...
    ~isempty(get(handles.CB_Mesh,'String'))&...
    ~isempty(get(handles.CB_Quiver,'String'))
    
    val=get(handles.CB_SwanRun,'Value');
    project=get(handles.TL_Project,'String');
    subrun=get(handles.CB_CGrid,'Value');
    
    tblfile=fullfile(project,sprintf('%02d-%s',subrun,...
        handles.m_Tables{val}));
    
    
    %display output data
    meshPar=cellstr(get(handles.CB_Mesh,'String'));
    meshPar=meshPar{get(handles.CB_Mesh,'Value')};
    quiverPar=cellstr(get(handles.CB_Quiver,'String'));
    quiverPar=quiverPar{get(handles.CB_Quiver,'Value')};
    
    
    %load Table data as SWANTBL Object
    data=SWANTbl(tblfile);
    
    
    %oleaje:
    [Mesh,X,Y]=data.genMesh(meshPar);
    meshDir=data.genMesh(quiverPar);
    
    %trick: to avoid problems with depth, swap depth<->elevations!
    if strcmp(meshPar,'Depth')
        Mesh=Mesh.*-1;
    end
    
    alphaBlank=isnan(Mesh); %to be used later in rotated grids!!
    
    [iLand,jLand]=find(Mesh<0); %ignore data lower than 0. (land)
    
    
    for k=1:length(iLand)
        Mesh(iLand(k),jLand(k)) = nan;
    end
    
    maxVal=max(Mesh(:));
    
    %axes(handles.axes1);
    cla(handles.axes1,'reset');
    cla(handles.cbar,'reset');
    imagesc('Parent',handles.axes1,'Xdata',X,'YData',Y,'CData',Mesh)
    set(handles.axes1,'CLim',[0 maxVal]);
    %set(handles.axes1,'YDir','normal');
    
    if exist('private\MapaOla.dat','file')
        mapaola=dlmread('private\MapaOla.dat');
    else
        mapaola=jet(256);
    end
    colormap(mapaola);
    
    colorbar(handles.cbar,'peer',handles.axes1);
    rect=get(handles.axes1,'position');
    cbrect=get(handles.cbar,'position');
    cbrect(4)=rect(4); %same height as axes1! (so image is nice)
    set(handles.cbar,'position',cbrect);
    axis(handles.axes1,'image','off');
    set(handles.axes1,'YDir','normal');
    
    %draw quiver
    hold(handles.axes1,'on');
    UDir=-sind(meshDir).*(Mesh./maxVal);
    VDir=cosd(meshDir).*(Mesh./maxVal);
    
    for k=1:length(iLand)
        UDir(iLand(k),jLand(k)) = 0;
        VDir(iLand(k),jLand(k)) = 0;
    end
    
    %show data every 4 elements.
    N=4;
    
    
    [XX,YY]=meshgrid(X,Y);
    
    quiver(handles.axes1,XX(1:N:end,1:N:end),YY(1:N:end,1:N:end),...
        UDir(1:N:end,1:N:end),-VDir(1:N:end,1:N:end),0.7,'color','k');
    
    
    coast=get(handles.TL_Coast,'String');
    
    if ~isempty(coast)
        cst=loadCst(coast);
        plotCst(handles.axes1,cst,[0.3 0.3 0.3]);
    end
    
    if data.isMeshRotated()
    Blank=ones([size(Mesh) 3]);   
    alphaBlank=alphaBlank*1;
    image('Parent',handles.axes1,'Xdata',X,'YData',Y,'CData',Blank,...
        'AlphaData',alphaBlank,'AlphaDataMapping','none');
    end
    
    
end


function TL_Coast_Callback(hObject, eventdata, handles)
% hObject    handle to TL_Coast (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of TL_Coast as text
%        str2double(get(hObject,'String')) returns contents of TL_Coast as a double


% --- Executes during object creation, after setting all properties.
function TL_Coast_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TL_Coast (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in PB_Coast.
function PB_Coast_Callback(hObject, eventdata, handles)
% hObject    handle to PB_Coast (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
file=fullfile(handles.Path,'*.cst');
[fname,fpath]=uigetfile(file,'Select coast file (.cst)');
costa=fullfile(fpath,fname);
set(handles.TL_Coast,'String',costa);
%updateDisplay(handles);


% --- Executes on selection change in CB_CGrid.
function CB_CGrid_Callback(hObject, eventdata, handles)
% hObject    handle to CB_CGrid (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns CB_CGrid contents as cell array
%        contents{get(hObject,'Value')} returns selected item from CB_CGrid


% --- Executes during object creation, after setting all properties.
function CB_CGrid_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_CGrid (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in CB_Mesh.
function CB_Mesh_Callback(hObject, eventdata, handles)
% hObject    handle to CB_Mesh (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns CB_Mesh contents as cell array
%        contents{get(hObject,'Value')} returns selected item from CB_Mesh


% --- Executes during object creation, after setting all properties.
function CB_Mesh_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_Mesh (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in CB_Quiver.
function CB_Quiver_Callback(hObject, eventdata, handles)
% hObject    handle to CB_Quiver (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns CB_Quiver contents as cell array
%        contents{get(hObject,'Value')} returns selected item from CB_Quiver


% --- Executes during object creation, after setting all properties.
function CB_Quiver_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_Quiver (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in PB_Update.
function PB_Update_Callback(hObject, eventdata, handles)
% hObject    handle to PB_Update (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
updateDisplay(handles);

% --- Executes on button press in P_Colormap.
function P_Colormap_Callback(hObject, eventdata, handles)
% hObject    handle to P_Colormap (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
colormapeditor(handles.figure1);


% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%uiresume(handles.figure1);
